import { SendService } from 'jdf-jssdk';
import { flatten, uniq, map } from 'lodash-es';
import { bizServiceURL } from '@/api/utils/constants';
import { alertErrorMsg, message, messageTipConfirm } from '@/api/utils/pc-message';

/*
 * @Author: lirl
 * @Date: 2023-04-09 22:08:09
 * @Description: 发送相关方法
 */
export default {
  methods: {
    /**
     * 获取主抄送字段
     */
    getSendOrgList() {
      const { subform } = this.$refs;
      const sendOrgFields = uniq([
        ...subform.needMainSendFields,
        ...map(flatten(subform.formConfigs).filter((t) => t.sendOrg), 'formElCode')
      ]);
      const { formData } = subform;
      return flatten(sendOrgFields.map((t) => formData[`${t}Selected`] ?? []));
    },
    /**
     * 打开发送部门弹窗进行重新选择，进行发送功能
     * @param {Object} button 点击的按钮对象
     * @param {String} piid 流程id
     * @param {Array} fileList 附件列表
     */
    async chooseDeptTransceiver(button, piid, fileList) {
      try {
        // 禁用原因：需修改按钮本身的loading状态
        // eslint-disable-next-line no-param-reassign
        button.loading = true;
        const { $refs: { subform }, customTemplateConfig } = this;
        const sendConfig = await subform.service?.getSendData?.(
          this.processDefinitionKey,
          customTemplateConfig.isGateWayData,
          true,
        );
        const { formData } = subform;
        this.renderConfig = {
          // 要渲染的组件
          type: () => import('@/components/SendForm'),
          // 组件的属性
          attrs: {
            treeTitle: '可选',
            piid,
            tiid: this.taskId,
            data: sendConfig.data,
            selectedDatas: this.getSendOrgList(),
            leaderList: flatten(customTemplateConfig.leaderFields.map(t => formData[`${t}Selected`] ?? [])),
            filterable: false,
            cols: sendConfig.cols,
            rows: sendConfig.rows,
            docNumber: formData.showSplit,
            processDefinitionKey: this.processDefinitionKey,
            files: fileList,
            isSetBack: formData.isSetBack,
            templateName: formData.templateName,
          },
          // 组件的事件
          on: {
            success: this.sendSuccessCallback,
          },
        };
        this.$nextTick(() => {
          this.renderVisible = true;
        });
      } catch (error) {
        alertErrorMsg(error);
      } finally {
        // 禁用原因：需修改按钮本身的loading状态
        // eslint-disable-next-line no-param-reassign
        button.loading = false;
      }
    },
    /**
     * 直接进行发送，无需重新选择发送部门
     */
    async directTransceiver(button, piid, fileList) {
      const { $refs } = this;
      if (!$refs.subform.formData.showSplit) {
        message('请填写文件编号！', 'warning');
        return;
      }
      const orgList = this.getSendOrgList();
      const { code, message: msg } = await new SendService(bizServiceURL).checkToSend(piid, orgList);
      if (code === '-1') {
        message(msg, 'warning');
        return;
      }
      if (code === '-2') {
        const info = msg.replace(
          '此公文已发送，请确认是否再次发送？',
          '<span style="red">此公文已发送，请确认是否再次发送？</span>'
        );
        messageTipConfirm(info, () => this.doSend(button, orgList, piid, fileList), null, '发送确认', {
          dangerouslyUseHTMLString: true,
        });
        return;
      }
      this.doSend(button, orgList, piid, fileList);
    },
    /**
     * 执行发送操作
     */
    doSend(button, orgList, piid, fileList) {
      messageTipConfirm(
        `文件将发送至${orgList.map(t => `${t.aliasPrefix ?? ''}${t.name}`).join(',')}转为部门收文，是否继续？`,
        async () => {
          try {
            // eslint-disable-next-line no-param-reassign
            button.loading = true;
            await new SendService(bizServiceURL).saveSendData(piid, orgList);
            message('发送成功');
            this.sendSuccessCallback(fileList);
          } catch (error) {
            alertErrorMsg(error);
          } finally {
            // eslint-disable-next-line no-param-reassign
            button.loading = false;
          }
        },
        null,
        '请确认'
      );
    },
    /**
     * 发送成功后回调
     */
    sendSuccessCallback(fileList) {
      this.$EventBus.$emit('bizEvent', {
        hideBtns: ['fileNumber', 'number'],
        showBtns: ['sendTrace']
      });
      this.$refs.subform.bizSave({ sendFlag: true }, fileList);
    },
  }
};
